﻿using AutoMapper;
using MediatR;
using Traceability_2203.Common.Domain;
using Traceability_2203.Common.Dto;
using Traceability_2203.Common.Infrastructure.interFaces;
using Traceability_2203.Enum;

namespace Traceability_2203.Api.Application.Commands.USer
{
    public class userCreateHander : IRequestHandler<USersCreateCommand, Reult>
    {

        private readonly IBaseRepository<Users> _userRepository;
        private readonly ILogger<userCreateHander> _logger;

        private readonly IMapper mapper;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userRepository"></param>
        public userCreateHander(IBaseRepository<Users> userRepository, ILogger<userCreateHander> logger, IMapper mapper)
        {
            _userRepository = userRepository;
            _logger = logger;   
            this.mapper = mapper;
        }
        /// <summary>
        /// 业务额逻
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Reult> Handle(USersCreateCommand request, CancellationToken cancellationToken)
        {


            var result = new Reult() { Code = (int)CommonErrorCode.Added };

            try
            {
           

                Users user = mapper.Map<Users>(request);
                var res = await _userRepository.Add(user);
                result.Code=(int)CommonErrorCode.Success;
              
            }
            catch (Exception ex)
            {
                _logger.LogError("[新增用户异常]"+ ex.Message);
                result.Msg = "新增失败";
                throw;
            }

            
            return result;
        }







    }
}
